package cn._51doit.flink.day02;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;

import java.util.Random;
import java.util.UUID;

/**
 *  RichXXXFunction 是功能更加丰富的Function，可以实现open、close方法，还可以调用getRuntimeContext(可以获取运行时的信息)
 *
 */
public class ParallelCustomSource3 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //可以认为设置执行环境的并行度
        //env.setParallelism(6);
        //System.out.println(env.getParallelism());

        DataStreamSource<String> lines = env.addSource(new ParallelMySource3());

        lines.print();

        env.execute();


    }

    private static class ParallelMySource3 extends RichParallelSourceFunction<String> {


        private boolean flag = true;

        @Override
        public void run(SourceContext<String> ctx) throws Exception {
            int indexOfThisSubtask = getRuntimeContext().getIndexOfThisSubtask();
            System.out.println("RUN method Invoked !!!  indexOfThisSubtask : " +  indexOfThisSubtask);
            //获取运行时上下文（获取Task运行时的信息）
            //Task的Index是从0开始的

            while (flag) {
                String str = UUID.randomUUID().toString();
                ctx.collect("task index is : " + indexOfThisSubtask + " content: " + str);
                Thread.sleep(2000);
            }
        }

        @Override
        public void cancel() {
            int indexOfThisSubtask = getRuntimeContext().getIndexOfThisSubtask();
            System.out.println("cancel method Invoked @@@  indexOfThisSubtask : " +  indexOfThisSubtask);
            flag = false;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            int indexOfThisSubtask = getRuntimeContext().getIndexOfThisSubtask();
            System.out.println("Open method Invoked ### indexOfThisSubtask : " +  indexOfThisSubtask);
        }

        @Override
        public void close() throws Exception {
            int indexOfThisSubtask = getRuntimeContext().getIndexOfThisSubtask();
            System.out.println("Close method Invoked $$$ indexOfThisSubtask : " +  indexOfThisSubtask);
        }
    }


}
